package team.scau.laboratory_repair.web.mobile.start.web;

import io.swagger.annotations.ApiOperation;
import lombok.extern.apachecommons.CommonsLog;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import team.scau.laboratory_repair.common.base.BaseController;
import team.scau.laboratory_repair.common.constant.ConstantRole;
import team.scau.laboratory_repair.common.constant.ConstantWebContext;
import team.scau.laboratory_repair.common.constant.ShiroConstant;
import team.scau.laboratory_repair.common.enums.LoginType;
import team.scau.laboratory_repair.common.enums.WechatUserType;
import team.scau.laboratory_repair.common.shiro.UserToken;
import team.scau.laboratory_repair.common.utils.Md5Utils;
import team.scau.laboratory_repair.common.utils.WechatTool;
import team.scau.laboratory_repair.modules.po.User;
import team.scau.laboratory_repair.modules.po.WechatUser;
import team.scau.laboratory_repair.service.UserService;
import team.scau.laboratory_repair.service.WechatUserService;
import team.scau.laboratory_repair.web.mobile.start.Service.HomePageService;

import javax.servlet.http.HttpSession;

/**
 * @Description:
 * @Author:ZTF
 * @Date:2018/5/22 15:47
 */
@RequestMapping("/mobile")
@Controller
@SessionAttributes(types = WechatUser.class,names = "WechatUser")
@CommonsLog
public class HomePageController extends BaseController {
    @Autowired
    private HomePageService homePageService;
    @Autowired
    private WechatUserService wechatUserService;
    @Autowired
    private UserService userService;

    @GetMapping("/start/login")
    @ApiOperation(value="返回移动端主界面", notes="")
    public String loginIndex(Model model) {
        return "/mobile/start/Login";
    }

    @GetMapping("/start/autologin")
    @ApiOperation(value="微信移动端自动登录的中继页面，可获得用户code", notes="")
    public String autoLogin(String code, String state, String nsukey,Model model, HttpSession session){
        WechatUser wechatUser;
        try{
            String openId = "";
            if(StringUtils.isNotBlank(code)){
                openId = WechatTool.getOpenId(code);
            }
            //如果openid不为空，存入session后续使用
            if(StringUtils.isNotBlank(openId)){
                session.setAttribute(ShiroConstant.REQUEST_OPEN_ID, openId);
            }

            wechatUser = wechatUserService.findByOpenId(openId);
            if(wechatUser != null){
                session.setAttribute(ShiroConstant.REQUEST_C_WECHAT_USER, wechatUser);
                if(wechatUser.getUserType() == WechatUserType.STAFF.getType()
                        || wechatUser.getUserType() == WechatUserType.LEADER.getType()){
                    session.setAttribute(ShiroConstant.REQUEST_C_USER, userService.getByPhoneNumber(wechatUser.getPhoneNumber()));
                }
            }
            else{
                return "redirect:/mobile/start/login";
            }
        }
        catch (Exception e){
            log.error(e.getMessage());
            return "redirect:/mobile/start/login";
        }
        switch (wechatUser.getUserType()){
            case 0:
                return "redirect:/mobile/registrant/homepage";
            case 1:
                return "redirect:/mobile/staff/homepage";
            case 2:
            default:
                return "redirect:/mobile/leader/homepage";
        }
    }


    @GetMapping("/start/register")
    @ApiOperation(value="返回微信端注册界面", notes="")
    public String register(Model model) {
        return "/mobile/start/register";
    }

    @PostMapping("/start/register")
    @ApiOperation(value="注册一名新的微信用户并返回结果页面", notes="")
    public String register(WechatUser wechatUser, RedirectAttributes redirectAttributes){
        try{
            //用户类型默认为0
            User user = userService.getByPhoneNumber(wechatUser.getPhoneNumber());
            if(user != null){
                //如果能在后台用户表里找到该电话号码，则其对应角色设置为微信账号的类型
                if(user.getRole().equals(ConstantRole.ROLE_STAFF)){
                    wechatUser.setUserType(WechatUserType.STAFF.getType());
                }
                else if(user.getRole().equals(ConstantRole.ROLE_MANAGER)){
                    wechatUser.setUserType(WechatUserType.LEADER.getType());
                }
            }
            else{
                //找不到，则默认为报修人类型
                wechatUser.setUserType(WechatUserType.REGISTRANT.getType());
            }
            wechatUser.setPassword(new Md5Utils().getkeyBeanofStr(wechatUser.getPassword()).toUpperCase());
            wechatUserService.save(wechatUser);
        }
        catch (Exception e){
            redirectAttributes.addFlashAttribute("message", "注册失败");
            return "redirect:/mobile/start/register";
        }
        return "redirect:/mobile/start/registersuccess";
    }

    @GetMapping("/start/registersuccess")
    @ApiOperation(value="返回微信端注册成功界面", notes="")
    public String registerSuccess(Model model) {
        return "/mobile/start/RegisterSuccess";
    }



    @PostMapping("/login.html")
    public String login(WechatUser wechatUser, Model model, HttpSession session
            , RedirectAttributes redirectAttributes) throws Exception {
        Subject current = SecurityUtils.getSubject();
        if(!current.isAuthenticated()){
            try {
                String password = new Md5Utils().getkeyBeanofStr(wechatUser.getPassword()).toUpperCase();
                UserToken userToken = new UserToken(wechatUser.getPhoneNumber(), password, LoginType.WECHAT_USER.toString());
                current.login(userToken);
            } catch (Exception e) {
                //可以写跳转的处理异常的页面
                model.addAttribute("message", "账号或者密码错误");
                model.addAttribute("openid", wechatUser.getOpenid());
                return "/mobile/start/Login";
            }
        }
        //登录成功后，如果数据库实体的openid为空，则将session中的openid填充
        //如果不为空，则将该openid写入session中
        WechatUser currentUser = wechatUserService.findByPhoneNumber(wechatUser.getPhoneNumber());
        String openid = getOpenId();
        if(StringUtils.isBlank(currentUser.getOpenid())){
            currentUser.setOpenid(openid);
            wechatUserService.save(currentUser);
        }
        else{
            session.setAttribute(ShiroConstant.REQUEST_OPEN_ID, currentUser.getOpenid());
        }

        session.setAttribute(ShiroConstant.REQUEST_C_WECHAT_USER, currentUser);
        if(currentUser.getUserType() == WechatUserType.STAFF.getType()
                || currentUser.getUserType() == WechatUserType.LEADER.getType()){
            session.setAttribute(ShiroConstant.REQUEST_C_USER, userService.getByPhoneNumber(currentUser.getPhoneNumber()));
        }

        switch (currentUser.getUserType()){
            case 0:
                return "redirect:/mobile/registrant/homepage";
            case 1:
                return "redirect:/mobile/staff/homepage";
            case 2:
            default:
                return "redirect:/mobile/leader/homepage";
        }
    }

    @GetMapping("/logout.html")
    public String logout(HttpSession session) throws Exception {
        try {
            SecurityUtils.getSubject().logout();
        }catch (Exception ex){
            ex.printStackTrace();
            log.error(ex.getMessage(), ex);
        }
        return "redirect:/mobile/start/login";
    }


}
